[[...path]].page.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, isClient, isIPageInfoForEntity, IUser, IUserHasId, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import ExtensibleCustomError from 'extensible-custom-error';
  7. import { model as mongooseModel } from 'mongoose';
  8. import {
  9. NextPage, GetServerSideProps, GetServerSidePropsContext,
  10. } from 'next';
  11. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  12. import dynamic from 'next/dynamic';
  13. import Head from 'next/head';
  14. import { useRouter } from 'next/router';
  15. import superjson from 'superjson';
  16. import { Comments } from '~/components/Comments';
  17. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  18. // import { useTranslation } from '~/i18n';
  19. import { CurrentPageContentFooter } from '~/components/PageContentFooter';
  20. import { UsersHomePageFooterProps } from '~/components/UsersHomePageFooter';
  21. import { CrowiRequest } from '~/interfaces/crowi-request';
  22. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  23. // import { useIndentSize } from '~/stores/editor';
  24. // import { useRendererSettings } from '~/stores/renderer';
  25. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  26. import { EditorConfig } from '~/interfaces/editor-settings';
  27. import { CustomWindow } from '~/interfaces/global';
  28. import { RendererConfig } from '~/interfaces/services/renderer';
  29. import { ISidebarConfig } from '~/interfaces/sidebar-config';
  30. import { IUserUISettings } from '~/interfaces/user-ui-settings';
  31. import { PageModel, PageDocument } from '~/server/models/page';
  32. import { PageRedirectModel } from '~/server/models/page-redirect';
  33. import { UserUISettingsModel } from '~/server/models/user-ui-settings';
  34. import { useSWRxCurrentPage, useSWRxIsGrantNormalized } from '~/stores/page';
  35. import { useRedirectFrom } from '~/stores/page-redirect';
  36. import {
  37. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth, useSelectedGrant,
  38. } from '~/stores/ui';
  39. import loggerFactory from '~/utils/logger';
  40. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  41. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  42. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  43. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  44. import { BasicLayout } from '../components/Layout/BasicLayout';
  45. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  46. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  47. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  48. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  49. import {
  50. useCurrentUser, useCurrentPagePath,
  51. useIsLatestRevision,
  52. useIsForbidden, useIsNotFound, useIsTrashPage, useIsSharedUser,
  53. useIsEnabledStaleNotification, useIsIdenticalPath,
  54. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  55. useHackmdUri,
  56. useIsAclEnabled, useIsUserPage,
  57. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  58. useIsSlackConfigured, useRendererConfig, useEditingMarkdown,
  59. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage,
  60. } from '../stores/context';
  61. import {
  62. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  63. } from './utils/commons';
  64. // import { useCurrentPageSWR } from '../stores/page';
  65. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  66. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  67. const UnsavedAlertDialog = dynamic(() => import('./UnsavedAlertDialog'), { ssr: false });
  68. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  69. const UsersHomePageFooter = dynamic<UsersHomePageFooterProps>(() => import('../components/UsersHomePageFooter')
  70. .then(mod => mod.UsersHomePageFooter), { ssr: false });
  71. const logger = loggerFactory('growi:pages:all');
  72. const {
  73. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage, isTopPage,
  74. } = pagePathUtils;
  75. const { removeHeadingSlash } = pathUtils;
  76. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  77. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  78. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  79. {
  80. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  81. return v?.data != null
  82. && v?.data.toObject != null
  83. && v?.meta != null
  84. && isIPageInfoForEntity(v.meta);
  85. },
  86. serialize: (v) => {
  87. return {
  88. data: superjson.stringify(v.data.toObject()),
  89. meta: superjson.stringify(v.meta),
  90. };
  91. },
  92. deserialize: (v) => {
  93. return {
  94. data: superjson.parse(v.data),
  95. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  96. };
  97. },
  98. },
  99. 'IPageToShowRevisionWithMetaTransformer',
  100. );
  101. const IdenticalPathPage = (): JSX.Element => {
  102. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  103. return <IdenticalPathPage />;
  104. };
  105. const PutbackPageModal = (): JSX.Element => {
  106. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  107. return <PutbackPageModal />;
  108. };
  109. type Props = CommonProps & {
  110. currentUser: IUser,
  111. pageWithMeta: IPageToShowRevisionWithMeta,
  112. // pageUser?: any,
  113. redirectFrom?: string;
  114. // shareLinkId?: string;
  115. isLatestRevision?: boolean
  116. isIdenticalPathPage?: boolean,
  117. isForbidden: boolean,
  118. isNotFound: boolean,
  119. IsNotCreatable: boolean,
  120. // isAbleToDeleteCompletely: boolean,
  121. isSearchServiceConfigured: boolean,
  122. isSearchServiceReachable: boolean,
  123. isSearchScopeChildrenAsDefault: boolean,
  124. isSlackConfigured: boolean,
  125. // isMailerSetup: boolean,
  126. isAclEnabled: boolean,
  127. // hasSlackConfig: boolean,
  128. // drawioUri: string,
  129. hackmdUri: string,
  130. // noCdn: string,
  131. // highlightJsStyle: string,
  132. isAllReplyShown: boolean,
  133. // isContainerFluid: boolean,
  134. editorConfig: EditorConfig,
  135. isEnabledStaleNotification: boolean,
  136. // isEnabledLinebreaks: boolean,
  137. // isEnabledLinebreaksInComments: boolean,
  138. // adminPreferredIndentSize: number,
  139. // isIndentSizeForced: boolean,
  140. disableLinkSharing: boolean,
  141. rendererConfig: RendererConfig,
  142. // UI
  143. userUISettings?: IUserUISettings
  144. // Sidebar
  145. sidebarConfig: ISidebarConfig,
  146. };
  147. const GrowiPage: NextPage<Props> = (props: Props) => {
  148. // const { t } = useTranslation();
  149. const router = useRouter();
  150. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  151. // register global EventEmitter
  152. if (isClient()) {
  153. (window as CustomWindow).globalEmitter = new EventEmitter();
  154. }
  155. // commons
  156. useEditorConfig(props.editorConfig);
  157. useCsrfToken(props.csrfToken);
  158. // UserUISettings
  159. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  160. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  161. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  162. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  163. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  164. // page
  165. useIsLatestRevision(props.isLatestRevision);
  166. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  167. useIsForbidden(props.isForbidden);
  168. useIsNotFound(props.isNotFound);
  169. // useIsNotCreatable(props.IsNotCreatable);
  170. useRedirectFrom(props.redirectFrom);
  171. // useIsTrashPage(_isTrashPage(props.currentPagePath));
  172. // useShared();
  173. // useShareLinkId(props.shareLinkId);
  174. useIsSharedUser(false); // this page cann't be routed for '/share'
  175. useIsIdenticalPath(false); // TODO: need to initialize from props
  176. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  177. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  178. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  179. useIsSearchServiceReachable(props.isSearchServiceReachable);
  180. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  181. useIsSlackConfigured(props.isSlackConfigured);
  182. // useIsMailerSetup(props.isMailerSetup);
  183. useIsAclEnabled(props.isAclEnabled);
  184. // useHasSlackConfig(props.hasSlackConfig);
  185. // useDrawioUri(props.drawioUri);
  186. useHackmdUri(props.hackmdUri);
  187. // useNoCdn(props.noCdn);
  188. // useIndentSize(props.adminPreferredIndentSize);
  189. useDisableLinkSharing(props.disableLinkSharing);
  190. useRendererConfig(props.rendererConfig);
  191. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  192. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  193. useIsAllReplyShown(props.isAllReplyShown);
  194. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  195. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  196. // const { data: editorMode } = useEditorMode();
  197. const { pageWithMeta, userUISettings } = props;
  198. let shouldRenderPutbackPageModal = false;
  199. if (pageWithMeta != null) {
  200. shouldRenderPutbackPageModal = _isTrashPage(pageWithMeta.data.path);
  201. }
  202. const pageId = pageWithMeta?.data._id;
  203. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  204. useCurrentPageId(pageId);
  205. useSWRxCurrentPage(undefined, pageWithMeta?.data); // store initial data
  206. useIsUserPage(isUserPage(pagePath));
  207. // useIsNotCreatable(props.isForbidden || !isCreatablePage(pagePath)); // TODO: need to include props.isIdentical
  208. useCurrentPagePath(pagePath);
  209. useCurrentPathname(props.currentPathname);
  210. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  211. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  212. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  213. // sync grant data
  214. useEffect(() => {
  215. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  216. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  217. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  218. useEffect(() => {
  219. const decodedURI = decodeURI(window.location.pathname);
  220. if (isClient() && decodedURI !== props.currentPathname) {
  221. router.replace(props.currentPathname, undefined, { shallow: true });
  222. }
  223. }, [props.currentPathname, router]);
  224. const classNames: string[] = [];
  225. // switch (editorMode) {
  226. // case EditorMode.Editor:
  227. // classNames.push('on-edit', 'builtin-editor');
  228. // break;
  229. // case EditorMode.HackMD:
  230. // classNames.push('on-edit', 'hackmd');
  231. // break;
  232. // }
  233. // if (page == null) {
  234. // classNames.push('not-found-page');
  235. // }
  236. const isTopPagePath = isTopPage(pageWithMeta?.data.path ?? '');
  237. return (
  238. <>
  239. <Head>
  240. {/*
  241. {renderScriptTagByName('drawio-viewer')}
  242. {renderScriptTagByName('highlight-addons')}
  243. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  244. */}
  245. </Head>
  246. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  247. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')} expandContainer={props.isContainerFluid}>
  248. <div className="h-100 d-flex flex-column justify-content-between">
  249. <header className="py-0 position-relative">
  250. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  251. </header>
  252. <div className="d-edit-none">
  253. <GrowiSubNavigationSwitcher />
  254. </div>
  255. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  256. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  257. <div className="flex-grow-1">
  258. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  259. <div id="content-main" className="content-main grw-container-convertible">
  260. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  261. { !props.isIdenticalPathPage && (
  262. <>
  263. <PageAlerts />
  264. { props.isForbidden && <ForbiddenPage /> }
  265. { props.IsNotCreatable && <NotCreatablePage />}
  266. { !props.isForbidden && !props.IsNotCreatable && <DisplaySwitcher />}
  267. {/* <DisplaySwitcher /> */}
  268. {/* <PageStatusAlert /> */}
  269. </>
  270. ) }
  271. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  272. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  273. <div id="revision-toc-content" className="revision-toc-content"></div>
  274. </div>
  275. </div> */}
  276. </div>
  277. </div>
  278. </div>
  279. { !props.isIdenticalPathPage && !props.isNotFound && (
  280. <footer className="footer d-edit-none">
  281. { !isTopPagePath && (<Comments pageId={pageId} revision={pageWithMeta?.data.revision} />) }
  282. { (pageWithMeta != null && isUsersHomePage(pageWithMeta.data.path)) && (
  283. <UsersHomePageFooter creatorId={pageWithMeta.data.creator._id}/>
  284. ) }
  285. <CurrentPageContentFooter />
  286. </footer>
  287. )}
  288. <UnsavedAlertDialog />
  289. <DescendantsPageListModal />
  290. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  291. </div>
  292. </BasicLayout>
  293. </>
  294. );
  295. };
  296. function getPageIdFromPathname(currentPathname: string): string | null {
  297. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  298. }
  299. class MultiplePagesHitsError extends ExtensibleCustomError {
  300. pagePath: string;
  301. constructor(pagePath: string) {
  302. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  303. this.pagePath = pagePath;
  304. }
  305. }
  306. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  307. const req: CrowiRequest = context.req as CrowiRequest;
  308. const { crowi } = req;
  309. const { revisionId } = req.query;
  310. const Page = crowi.model('Page') as PageModel;
  311. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  312. const { pageService } = crowi;
  313. let currentPathname = props.currentPathname;
  314. const pageId = getPageIdFromPathname(currentPathname);
  315. const isPermalink = _isPermalink(currentPathname);
  316. const { user } = req;
  317. if (!isPermalink) {
  318. // check redirects
  319. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  320. if (chains != null) {
  321. // overwrite currentPathname
  322. currentPathname = chains.end.toPath;
  323. props.currentPathname = currentPathname;
  324. // set redirectFrom
  325. props.redirectFrom = chains.start.fromPath;
  326. }
  327. // check whether the specified page path hits to multiple pages
  328. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  329. if (count > 1) {
  330. throw new MultiplePagesHitsError(currentPathname);
  331. }
  332. }
  333. const pageWithMeta: IPageToShowRevisionWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  334. const page = pageWithMeta?.data as unknown as PageDocument;
  335. // populate & check if the revision is latest
  336. if (page != null) {
  337. page.initLatestRevisionField(revisionId);
  338. await page.populateDataToShowRevision();
  339. props.isLatestRevision = page.isLatestRevision();
  340. }
  341. props.pageWithMeta = pageWithMeta;
  342. }
  343. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  344. const req = context.req as CrowiRequest<IUserHasId & any>;
  345. const { user } = req;
  346. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  347. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  348. if (userUISettings != null) {
  349. props.userUISettings = userUISettings.toObject();
  350. }
  351. }
  352. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  353. const req: CrowiRequest = context.req as CrowiRequest;
  354. const { crowi } = req;
  355. const Page = crowi.model('Page') as PageModel;
  356. const { currentPathname } = props;
  357. const pageId = getPageIdFromPathname(currentPathname);
  358. const isPermalink = _isPermalink(currentPathname);
  359. const page = props.pageWithMeta?.data;
  360. if (props.isIdenticalPathPage) {
  361. // TBD
  362. }
  363. else if (page == null) {
  364. props.isNotFound = true;
  365. props.IsNotCreatable = !isCreatablePage(currentPathname);
  366. // check the page is forbidden or just does not exist.
  367. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  368. props.isForbidden = count > 0;
  369. }
  370. else {
  371. props.isNotFound = page.isEmpty;
  372. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  373. if (isPermalink && page.isEmpty) {
  374. props.currentPathname = page.path;
  375. }
  376. // /path/to/page ==> /62a88db47fed8b2d94f30000
  377. if (!isPermalink && !page.isEmpty) {
  378. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  379. if (!isToppage) {
  380. props.currentPathname = `/${page._id}`;
  381. }
  382. }
  383. }
  384. }
  385. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  386. // const req: CrowiRequest = context.req as CrowiRequest;
  387. // const { crowi } = req;
  388. // const UserModel = crowi.model('User');
  389. // if (isUserPage(props.currentPagePath)) {
  390. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  391. // if (user != null) {
  392. // props.pageUser = JSON.stringify(user.toObject());
  393. // }
  394. // }
  395. // }
  396. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  397. const req: CrowiRequest = context.req as CrowiRequest;
  398. const { crowi } = req;
  399. const {
  400. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  401. } = crowi;
  402. props.isSearchServiceConfigured = searchService.isConfigured;
  403. props.isSearchServiceReachable = searchService.isReachable;
  404. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  405. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  406. // props.isMailerSetup = mailService.isMailerSetup;
  407. props.isAclEnabled = aclService.isAclEnabled();
  408. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  409. // props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  410. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  411. // props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  412. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  413. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  414. // props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  415. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  416. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  417. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  418. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  419. props.editorConfig = {
  420. upload: {
  421. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  422. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  423. },
  424. };
  425. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  426. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  427. props.rendererConfig = {
  428. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  429. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  430. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  431. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  432. plantumlUri: process.env.PLANTUML_URI ?? null,
  433. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  434. // XSS Options
  435. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  436. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  437. tagWhiteList: crowi.xssService.getTagWhiteList(),
  438. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  439. };
  440. props.sidebarConfig = {
  441. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  442. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  443. };
  444. }
  445. /**
  446. * for Server Side Translations
  447. * @param context
  448. * @param props
  449. * @param namespacesRequired
  450. */
  451. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  452. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  453. props._nextI18Next = nextI18NextConfig._nextI18Next;
  454. }
  455. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  456. const req = context.req as CrowiRequest<IUserHasId & any>;
  457. const { user } = req;
  458. const result = await getServerSideCommonProps(context);
  459. // check for presence
  460. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  461. if (!('props' in result)) {
  462. throw new Error('invalid getSSP result');
  463. }
  464. const props: Props = result.props as Props;
  465. if (props.redirectDestination != null) {
  466. return {
  467. redirect: {
  468. permanent: false,
  469. destination: props.redirectDestination,
  470. },
  471. };
  472. }
  473. if (user != null) {
  474. props.currentUser = user.toObject();
  475. }
  476. try {
  477. await injectPageData(context, props);
  478. }
  479. catch (err) {
  480. if (err instanceof MultiplePagesHitsError) {
  481. props.isIdenticalPathPage = true;
  482. }
  483. else {
  484. throw err;
  485. }
  486. }
  487. await injectUserUISettings(context, props);
  488. await injectRoutingInformation(context, props);
  489. injectServerConfigurations(context, props);
  490. await injectNextI18NextConfigurations(context, props, ['translation']);
  491. return {
  492. props,
  493. };
  494. };
  495. export default GrowiPage;